package com.whmskj.xjlhbc.mobile.schedule;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.*;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.whmskj.xjlhbc.db.DataSourceType;
import com.whmskj.xjlhbc.db.DynamicDataSourceContextHolder;
import com.whmskj.xjlhbc.domain.*;
import com.whmskj.xjlhbc.mapper.Js05dVarietyMaintenanceMapper;
import com.whmskj.xjlhbc.mapper.MachineInfoMapper;
import com.whmskj.xjlhbc.mapper.SczbjMapper;
import com.whmskj.xjlhbc.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

@Slf4j
@Component
public class StatisticsTask {

    @Autowired
    private IStatisticsService statisticsService;

    @Autowired
    private IStatisticsDayService statisticsDayService;

    @Autowired
    private MachineInfoMapper machineInfoMapper;

    @Autowired
    private IRundataInfoService rundataInfoService;

    @Autowired
    private IStopdataInfoService stopdataInfoService;

    @Autowired
    private IStopdataInfoClassService stopdataInfoClassService;

    @Autowired
    private IStopdataInfoHistoryService stopdataInfoHistoryService;

    @Autowired
    private IRundataInfoHistoryService rundataInfoHistoryService;

    @Autowired
    private Js05dVarietyMaintenanceMapper js05dVarietyMaintenanceMapper;

    @Autowired
    private SczbjMapper sczbjMapper;

    private static String TOKEN;
    private List<MachineInfo> machineInfos = new ArrayList<>();

    @PostConstruct
    public void getMachineInfos(){
        machineInfos = machineInfoMapper.selectList(null);
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void saveStatistics(){
        List<Statistics> statisticsList = new ArrayList<>();
        List<StatisticsDay> statisticsDayList = new ArrayList<>();
        List<StopdataInfoClass> stopdataInfoList = new ArrayList<>();
        List<MacInfo> macInfoList = getMacInfoList();
        macInfoList.forEach(macInfo -> {
            String macid = macInfo.getMacid();
            Classreport classreport = macInfo.getClassreport();
            String classname = classreport.getClassname();
            String startdatetime = classreport.getStartdatetime();
            LambdaQueryWrapper<Statistics> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Statistics::getMacid, macid).eq(Statistics::getClassname, classname)
                    .eq(Statistics::getStartdatetime, startdatetime).last("limit 1");
            Statistics statistics = Optional.ofNullable(statisticsService.getOne(wrapper)).orElseGet(Statistics::new);
            statistics.setMacid(macid);
            statistics.setClassname(classname);
            statistics.setDateymd(startdatetime.substring(0,10));
            statistics.setRuntime(classreport.getRuntime());
            statistics.setRuntime_format(convertSeconds(classreport.getRuntime()));
            statistics.setEmployee(classreport.getEmployee());
            statistics.setStartdatetime(DateUtil.parse(startdatetime));
            statistics.setVariety(StringUtils.trimAllWhitespace(classreport.getVariety()));
            statistics.setWeftdensity(macInfo.getRealtimeinfo().getWeftdensity());
            statistics.setVarietydatetime(DateUtil.parse(classreport.getVarietydatetime()));
            statistics.setSpeed(String.valueOf(macInfo.getRealtimeinfo().getSpeed()));
            statistics.setEfficiency(String.valueOf(classreport.getEfficiency()));
            statistics.setClothlength(String.valueOf(classreport.getClothlength()));
            statistics.setClothlength_zb(String.format("%.2f",getZb(statistics.getVariety()) * classreport.getClothlength()));
            statistics.setUpdatetime(DateUtil.parse(macInfo.getUpdatetime()));
            statisticsList.add(statistics);

            LambdaQueryWrapper<StopdataInfoClass> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StopdataInfoClass::getMacid, macid).eq(StopdataInfoClass::getClassname, classname)
                    .eq(StopdataInfoClass::getStartdatetime, startdatetime).last("limit 1");
            StopdataInfoClass stopdataInfo = Optional.ofNullable(stopdataInfoClassService.getOne(queryWrapper)).orElseGet(StopdataInfoClass::new);
            stopdataInfo.setMacid(macid);
            stopdataInfo.setClassname(classname);
            stopdataInfo.setRuntime(classreport.getRuntime());
            stopdataInfo.setRuntime_format(convertSeconds(classreport.getRuntime()));
            stopdataInfo.setStartdatetime(startdatetime);
            stopdataInfo.setDateymd(startdatetime.substring(0,10));
            stopdataInfo.setStopcount_total(classreport.getStopcountTotal());
            stopdataInfo.setStoptime_total(classreport.getStoptimeTotal());
            stopdataInfo.setStoptime_total_format(convertSeconds(classreport.getStoptimeTotal()));
            stopdataInfo.setStopcount_warp(classreport.getStopcountWarp());
            stopdataInfo.setStoptime_warp(classreport.getStoptimeWarp());
            stopdataInfo.setStoptime_warp_format(convertSeconds(classreport.getStoptimeWarp()));
            stopdataInfo.setStopcount_weft_short(classreport.getStopcountWeft().getS().getTotal());
            stopdataInfo.setStoptime_weft_short(classreport.getStoptimeWeft().getS().getTotal());
            stopdataInfo.setStoptime_weft_short_format(convertSeconds(classreport.getStoptimeWeft().getS().getTotal()));
            stopdataInfo.setStopcount_weft_long(classreport.getStopcountWeft().getL().getTotal());
            stopdataInfo.setStoptime_weft_long(classreport.getStoptimeWeft().getL().getTotal());
            stopdataInfo.setStoptime_weft_long_format(convertSeconds(classreport.getStoptimeWeft().getL().getTotal()));
            stopdataInfo.setStopcount_other(classreport.getStopcountOther());
            stopdataInfo.setStoptime_other(classreport.getStoptimeOther());
            stopdataInfo.setStoptime_other_format(convertSeconds(classreport.getStoptimeOther()));
            stopdataInfo.setUpdatetime(DateUtil.parse(macInfo.getUpdatetime()));
            stopdataInfoList.add(stopdataInfo);
        });
        statisticsService.saveOrUpdateBatch(statisticsList);
        ThreadUtil.execAsync(() -> {
            stopdataInfoClassService.saveOrUpdateBatch(stopdataInfoList);
        });

        macInfoList.forEach(macInfo -> {
            DateTime date = DateUtil.date();
            String now = DateUtil.hour(date,true) <= 10 ? DateUtil.offsetDay(date,-1).toDateStr() : date.toDateStr();
            String macid = macInfo.getMacid();
            LambdaQueryWrapper<StatisticsDay> statisticsDayLambdaQueryWrapper = new LambdaQueryWrapper<>();
            statisticsDayLambdaQueryWrapper.eq(StatisticsDay::getMacid, macid).eq(StatisticsDay::getDateymd, now).last("limit 1");
            LambdaQueryWrapper<Statistics> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Statistics::getMacid, macid).eq(Statistics::getDateymd, now);
            List<Statistics> statistics = statisticsService.list(wrapper);
            double sum = statistics.stream().mapToDouble(s -> NumberUtil.parseDouble(s.getClothlength(), 0.0)).sum();
            double zbSum = statistics.stream().mapToDouble(s -> NumberUtil.parseDouble(s.getClothlength_zb(), 0.0)).sum();
            StatisticsDay statisticsDay = Optional.ofNullable(statisticsDayService.getOne(statisticsDayLambdaQueryWrapper)).orElseGet(StatisticsDay::new);
            statisticsDay.setMacid(macid);
            statisticsDay.setDateymd(now);
            statisticsDay.setWeftdensity(macInfo.getRealtimeinfo().getWeftdensity());
            statisticsDay.setClothlength(String.format("%.2f",sum));
            statisticsDay.setClothlength_zb(String.format("%.2f",zbSum));
            statisticsDay.setUpdatetime(DateUtil.parse(macInfo.getUpdatetime()));
            statisticsDayList.add(statisticsDay);
        });
        statisticsDayService.saveOrUpdateBatch(statisticsDayList);
    }

    private Js05dVarietyMaintenance getJs05dVarietyMaintenance(String variety){
        LambdaQueryWrapper<Js05dVarietyMaintenance> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Js05dVarietyMaintenance::getNoNo3, variety).last("limit 1");
        return Optional.ofNullable(js05dVarietyMaintenanceMapper.selectOne(wrapper)).orElseGet(Js05dVarietyMaintenance::new);
    }

    private double getZb(String variety){
        Js05dVarietyMaintenance js05dVarietyMaintenance = getJs05dVarietyMaintenance(variety);
        double v = Optional.ofNullable(js05dVarietyMaintenance.getDiscountFactor()).orElse(1.0);
        return v > 0 ? v : 1;
    }

    private double getShrinkRate(String variety){
        Js05dVarietyMaintenance js05dVarietyMaintenance = getJs05dVarietyMaintenance(variety);
        double v = Optional.ofNullable(js05dVarietyMaintenance.getShrinkRate()).orElse(0.0);
        return (100.0 - v)/100.0;
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void saveRundataInfo(){
        List<RundataInfo> rundataInfoList = new ArrayList<>();
        List<StopdataInfo> stopdataInfoList = new ArrayList<>();
        List<StopdataInfoHistory> stopdataInfoHistoryList = new ArrayList<>();
        List<MacInfo> macInfoList = getMacInfoList();
        macInfoList.forEach(macInfo -> {
            String macid = macInfo.getMacid();
            Realtimeinfo realtimeinfo = macInfo.getRealtimeinfo();
            Classreport classreport = macInfo.getClassreport();
            RundataInfo rundataInfo = getRundataInfo(macid, realtimeinfo, classreport);
            rundataInfoList.add(rundataInfo);

            LambdaQueryWrapper<StopdataInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(StopdataInfo::getMacid, macid).last("limit 1");
            StopdataInfo stopdataInfo = Optional.ofNullable(stopdataInfoService.getOne(queryWrapper)).orElseGet(StopdataInfo::new);
            stopdataInfo.setMacid(macid);
            stopdataInfo.setStopcount_total(classreport.getStopcountTotal());
            stopdataInfo.setStoptime_total(classreport.getStoptimeTotal());
            stopdataInfo.setStoptime_total_format(convertSeconds(classreport.getStoptimeTotal()));
            stopdataInfo.setStopcount_warp(classreport.getStopcountWarp());
            stopdataInfo.setStoptime_warp(classreport.getStoptimeWarp());
            stopdataInfo.setStoptime_warp_format(convertSeconds(classreport.getStoptimeWarp()));
            stopdataInfo.setStopcount_weft_short(classreport.getStopcountWeft().getS().getTotal());
            stopdataInfo.setStoptime_weft_short(classreport.getStoptimeWeft().getS().getTotal());
            stopdataInfo.setStoptime_weft_short_format(convertSeconds(classreport.getStoptimeWeft().getS().getTotal()));
            stopdataInfo.setStopcount_weft_long(classreport.getStopcountWeft().getL().getTotal());
            stopdataInfo.setStoptime_weft_long(classreport.getStoptimeWeft().getL().getTotal());
            stopdataInfo.setStoptime_weft_long_format(convertSeconds(classreport.getStoptimeWeft().getL().getTotal()));
            stopdataInfo.setStopcount_other(classreport.getStopcountOther());
            stopdataInfo.setStoptime_other(classreport.getStoptimeOther());
            stopdataInfo.setStoptime_other_format(convertSeconds(classreport.getStoptimeOther()));
            stopdataInfo.setTs(DateUtil.now());
            stopdataInfoList.add(stopdataInfo);

            MachineInfo minfo = new MachineInfo();
            minfo.setLoomstate(rundataInfo.getLoomstate());
            LambdaUpdateWrapper<MachineInfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(MachineInfo::getCustomid, macid);
            machineInfoMapper.update(minfo, updateWrapper);

            if(rundataInfo.getLoomstate().equals("临停")){
                StopdataInfoHistory stopdataInfoHistory = new StopdataInfoHistory();
                stopdataInfoHistory.setMacid(macid);
                stopdataInfoHistory.setDateymd(DateUtil.today());
                stopdataInfoHistory.setStartdatetime(DateUtil.now());
                stopdataInfoHistory.setStopreason(rundataInfo.getStopreason());
                stopdataInfoHistoryList.add(stopdataInfoHistory);
            }
        });
        rundataInfoService.saveOrUpdateBatch(rundataInfoList);
        stopdataInfoService.saveOrUpdateBatch(stopdataInfoList);
        stopdataInfoHistoryService.saveOrUpdateBatch(stopdataInfoHistoryList);
    }

    @Scheduled(cron = "0 0 10,16,22 * * ?")
    public void saveRundataInfoHistory(){
        List<RundataInfoHistory> rundataInfoHistoryList = new ArrayList<>();
        List<MacInfo> macInfoList = getMacInfoList();
        macInfoList.forEach(macInfo -> {
            String macid = macInfo.getMacid();
            Realtimeinfo realtimeinfo = macInfo.getRealtimeinfo();
            Classreport classreport = macInfo.getClassreport();
            RundataInfo rundataInfo = getRundataInfo(macid, realtimeinfo, classreport);
            RundataInfoHistory rundataInfoHistory = new RundataInfoHistory();
            BeanUtils.copyProperties(rundataInfo, rundataInfoHistory);
            rundataInfoHistoryList.add(rundataInfoHistory);
        });
        rundataInfoHistoryService.saveOrUpdateBatch(rundataInfoHistoryList);
    }

    private RundataInfo getRundataInfo(String macid,Realtimeinfo realtimeinfo,Classreport classreport){
        String startdatetime = classreport.getStartdatetime();
        int warpbeamGroundDatetime = realtimeinfo.getWarpbeamGroundDatetime();
        int piececutDatetime = realtimeinfo.getPiececutDatetime();
        DateTime dateTime = DateUtil.offsetSecond(new Date(), warpbeamGroundDatetime);
        DateTime dateTime1 = DateUtil.offsetSecond(new Date(), piececutDatetime);
        LambdaQueryWrapper<RundataInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RundataInfo::getMacid, macid).last("limit 1");
        RundataInfo rundataInfo = Optional.ofNullable(rundataInfoService.getOne(wrapper)).orElseGet(RundataInfo::new);
        rundataInfo.setMacid(macid);
        rundataInfo.setClassname(classreport.getClassname());
        rundataInfo.setVariety(StringUtils.trimAllWhitespace(classreport.getVariety()));
        rundataInfo.setEmployee(classreport.getEmployee());
        rundataInfo.setLoomstate(getLoomstate(realtimeinfo.getLoomstate()));
        rundataInfo.setEfficiency(classreport.getEfficiency());
        rundataInfo.setClothlength(classreport.getClothlength());
        rundataInfo.setSpeed(realtimeinfo.getSpeed());
        rundataInfo.setWeftcount(classreport.getWeftcount());
        rundataInfo.setWeftdensity(realtimeinfo.getWeftdensity());
        rundataInfo.setTension_celestial_set(realtimeinfo.getTensionCelestialSet());
        rundataInfo.setTension_celestial_actual(realtimeinfo.getTensionCelestialActual());
        rundataInfo.setTension_ground_actual(realtimeinfo.getTensionGroundActual());
        rundataInfo.setTension_ground_set(realtimeinfo.getTensionGroundSet());
        rundataInfo.setStartdatetime(startdatetime);
        rundataInfo.setRuntime(classreport.getRuntime());
        rundataInfo.setRuntime_format(convertSeconds(classreport.getRuntime()));
        rundataInfo.setPiececut_datetime(dateTime1);
        rundataInfo.setPiececut_set(realtimeinfo.getPiececutSet());
        rundataInfo.setPiececut_woven(realtimeinfo.getPiececutWoven());
        rundataInfo.setPiececut_progress(String.format("%.2f",rundataInfo.getPiececut_woven()/ rundataInfo.getPiececut_set() * 100));
        rundataInfo.setPiececut_length(rundataInfo.getPiececut_woven() + "/" + rundataInfo.getPiececut_set());
        rundataInfo.setWarpbeam_ground_datetime(dateTime.toString());
        double shrinkRate = getShrinkRate(rundataInfo.getVariety());
        long v1 = (long) (warpbeamGroundDatetime * shrinkRate);
        long v = v1 * 1000L;
        rundataInfo.setSyscm(warpbeamGroundDatetime);
        rundataInfo.setSyscmsl(v1);
        rundataInfo.setSysc(DateUtil.formatBetween(v, BetweenFormatter.Level.MINUTE));
        rundataInfo.setWarpbeam_celestial_total(realtimeinfo.getWarpbeamCelestialTotal());
        rundataInfo.setWarpbeam_celestial_woven(realtimeinfo.getWarpbeamCelestialWoven());
        rundataInfo.setWarpbeam_celestial_progress(String.format("%.2f",(realtimeinfo.getWarpbeamGroundTotal() - realtimeinfo.getWarpbeamGroundWoven())/realtimeinfo.getWarpbeamGroundTotal() * 100));
        rundataInfo.setWarpbeam_celestial_length((long)realtimeinfo.getWarpbeamGroundWoven() + "/" + realtimeinfo.getWarpbeamGroundTotal());
        rundataInfo.setWarpbeam_ground_woven((long)realtimeinfo.getWarpbeamGroundWoven());
        rundataInfo.setWarpbeam_ground_total(realtimeinfo.getWarpbeamGroundTotal());
        rundataInfo.setAlarm(realtimeinfo.getAlarm());
        rundataInfo.setStopreason(realtimeinfo.getStopreason());
        rundataInfo.setMacangle(realtimeinfo.getMacangle());
        rundataInfo.setBrakeangle_start(realtimeinfo.getBrakeangleStart());
        rundataInfo.setBrakeangle_end(realtimeinfo.getBrakeangleEnd());
        rundataInfo.setBrakeangle_distance(realtimeinfo.getBrakeangleDistance());
        rundataInfo.setTs(DateUtil.now());
        return rundataInfo;
    }

    @Scheduled(cron = "0/2 * * * * ?")
    public void getZbj(){
        try {
            ObjectMapper mapper = new ObjectMapper();
            List<List<MachineInfo>> listMachineInfoList = CollUtil.split(machineInfos, 10);
            listMachineInfoList.forEach(ele-> CompletableFuture.runAsync(() -> {
                DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SC.name());
                ele.forEach(machineInfo -> {
                    MacInfo macInfo = get(machineInfo.getMacid());
                    if(Objects.isNull(macInfo))return;
                    String macid = machineInfo.getCustomid();
                    macInfo.setMacid(macid);
                    String startdatetime = macInfo.getClassreport().getStartdatetime();
                    Sczbj entity = new Sczbj();
                    entity.setUpdatetime(macInfo.getUpdatetime());
                    try {
                        entity.setOrigin(mapper.writeValueAsString(macInfo));
                    } catch (JsonProcessingException e) {}
                    entity.setCreatetime(new Date());
                    LambdaQueryWrapper<Sczbj> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(Sczbj::getMacid, macid);
                    wrapper.eq(Sczbj::getStartdatetime, startdatetime);

                    int update = sczbjMapper.update(entity, wrapper);
                    if(update == 0) {
                        entity.setMacid(macid);
                        entity.setStartdatetime(startdatetime);
                        sczbjMapper.insert(entity);
                    }
                });
                DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MASTER.name());
            }));
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    private List<MacInfo> getMacInfoList(){
        try {
            DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.SC.name());
            DateTime date = DateUtil.date();
            int hour = date.hour(true);
            int startHour = 9;
            if(hour <= startHour){
                date.offset(DateField.DAY_OF_MONTH, -1);
            }
            String dateStr = date.toDateStr();
            if(hour <= startHour || hour>21){
                dateStr += " 21:00:00";
            }
            if (hour > startHour && hour <= 21) {
                dateStr += " 09:00:00";
            }
            LambdaQueryWrapper<Sczbj> wrapper = new LambdaQueryWrapper<>();
            wrapper.ge(Sczbj::getStartdatetime, dateStr);
            List<Sczbj> sczbjList = sczbjMapper.selectList(wrapper);
            ObjectMapper mapper = new ObjectMapper();
            List<MacInfo> list = sczbjList.stream().filter(f -> f.getMacid().length() > 3).map(ele -> {
                MacInfo macInfo = null;
                try {
                    macInfo = mapper.readValue(ele.getOrigin(), MacInfo.class);
                    macInfo.setMacid(ele.getMacid());
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                return macInfo;
            }).collect(Collectors.toList());
            List<MacInfo> list1 = sczbjList.stream().filter(f -> f.getMacid().length() == 3).map(ele -> {
                MacInfo macInfo = new MacInfo();
                try {
                    MacInfo1 macInfo1 = mapper.readValue(ele.getOrigin(), MacInfo1.class);
                    macInfo.setMacid(macInfo1.getD0());
                    macInfo.setMacid(macInfo1.getD0());
                    macInfo.setUpdatetime(ele.getUpdatetime());
                    Classreport classreport = new Classreport();
                    Realtimeinfo realtimeinfo = new Realtimeinfo();
                    macInfo.setClassreport(classreport);
                    macInfo.setRealtimeinfo(realtimeinfo);
                    realtimeinfo.setLoomstate(macInfo1.getD5() == 1 ? "快车" : "临停");
                    realtimeinfo.setSpeed(macInfo1.getD32());
                    realtimeinfo.setWeftdensity(macInfo1.getD41());
                    realtimeinfo.setVariety(macInfo1.getD1());
                    realtimeinfo.setWarpbeamCelestialTotal(macInfo1.getD6());
                    realtimeinfo.setWarpbeamCelestialWoven((int) macInfo1.getD7());
                    realtimeinfo.setWarpbeamGroundDatetime(macInfo1.getD45());
                    realtimeinfo.setWarpbeamGroundTotal(macInfo1.getD6());
                    realtimeinfo.setWarpbeamGroundWoven(macInfo1.getD7());
                    realtimeinfo.setPiececutDatetime(macInfo1.getD44());
                    realtimeinfo.setPiececutSet(macInfo1.getD9());
                    realtimeinfo.setPiececutWoven(macInfo1.getD10());
                    realtimeinfo.setTensionCelestialSet(macInfo1.getD46());
                    realtimeinfo.setTensionCelestialActual(macInfo1.getD47());
                    realtimeinfo.setTensionGroundSet(macInfo1.getD46());
                    realtimeinfo.setTensionGroundActual(macInfo1.getD47());


                    classreport.setClassname(macInfo1.getD50());
                    classreport.setEmployee("");
                    classreport.setStartdatetime(ele.getStartdatetime());
                    classreport.setVariety(macInfo1.getD1());
                    classreport.setVarietydatetime(ele.getStartdatetime());
                    classreport.setEfficiency(macInfo1.getD14());
                    classreport.setClothlength(macInfo1.getD12());
                    classreport.setWeftcount(macInfo1.getD13());
                    long second = DateUtil.between(DateUtil.parse(ele.getStartdatetime()), new Date(), DateUnit.SECOND);
                    classreport.setRuntime((int) second);
                    classreport.setStopcountTotal(1);
                    classreport.setStoptimeTotal(1);
                    classreport.setStopcountWarp(macInfo1.getD24());
                    classreport.setStoptimeWarp(macInfo1.getD17());
                    classreport.setStopcountOther(macInfo1.getD21());
                    classreport.setStoptimeOther(macInfo1.getD20());
                    classreport.setStopcountWeftfeeder(macInfo1.getD19());
                    StopcountWeft stopcountWeft = classreport.getStopcountWeft();
                    StopcountWeft stoptimeWeft = classreport.getStoptimeWeft();
                    StopShortLong stopShort = new StopShortLong();
                    StopShortLong stopLong = new StopShortLong();
                    stopShort.setTotal(macInfo1.getD25());
                    stopLong.setTotal(macInfo1.getD26());
                    stopcountWeft.setS(stopShort);
                    stopcountWeft.setL(stopLong);
                    stopShort.setTotal(macInfo1.getD23());
                    stopLong.setTotal(macInfo1.getD22());
                    stoptimeWeft.setS(stopShort);
                    stoptimeWeft.setL(stopLong);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                return macInfo;
            }).collect(Collectors.toList());
            list.addAll(list1);
            return list;
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }

    private static String convertSeconds(int seconds) {
        int hours = Math.floorDiv(seconds, 3600);
        int minutes = Math.floorDiv(seconds % 3600, 60);
        int remainingSeconds = seconds % 60;
        return String.format("%02d:%02d:%02d", hours, minutes, remainingSeconds);
    }

    private String getLoomstate(String loomstate) {
        if(!StringUtils.hasText(loomstate))
            return loomstate;
        return loomstate.equals("快车") ? "运行" : loomstate.equals("离线") ? "离线" : "临停";
    }

    private MacInfo get(String macid) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            if (!StringUtils.hasText(TOKEN)) {
                Map<String, String> map = new HashMap<>();
                map.put("username", "lihua");
                map.put("password", "lh@1234");
                String body = mapper.writeValueAsString(map);
                String response = HttpUtil.post("https://www.rifatmiot.com/api/user/Login", body);
                Map<String,Object> responseMap = mapper.readValue(response, Map.class);
                int code = (int) responseMap.get("code");
                if (code != 0) {
                    log.error(response);
                    return null;
                }
                Map<String, Object> data = (Map<String, Object>) responseMap.get("data");
                TOKEN = data.get("token").toString();
            }
            HttpRequest get = HttpUtil.createGet("https://www.rifatmiot.com/api/business/LoomRealtimeDetailInfo");
            get.header("X-Access-Token", TOKEN);
            get.form("macid", macid);
            HttpResponse execute = get.execute();
            String infoResponse = execute.body();
            Map<String,Object> responseMap = mapper.readValue(infoResponse, Map.class);
            int code = (int) responseMap.get("code");
            if (code != 0) {
                TOKEN = "";
                return get(macid);
            }
            return mapper.readValue(mapper.writeValueAsString(responseMap.get("data")), MacInfo.class);
        }catch (Exception e){
            return null;
        }
    }
}
